import { prevent } from '../utils'
import { API, resolves } from '../api'
import { CydonElement, define } from 'cydon'

const hideDropzone = (e: Event) => {
	prevent(e)
	setTimeout(() =>
		API.setDropzone(0, 0, 0), 1000)
}

/** 初始化拖拽区域 */
const initDropzone = (el: HTMLElement) => {
	el.addEventListener('dragover', prevent)
	el.addEventListener('drop', hideDropzone)
	document.addEventListener('dragleave', hideDropzone)
	document.addEventListener('dragenter', () => {
		const rect = el.getBoundingClientRect()
		API.setDropzone(rect.x | 0, rect.y | 0,
			Math.ceil(rect.width) + 1, Math.ceil(rect.height) + 1)
	})
}

/**
 * @element upload-zone
 * 上传区域
 */
@define('upload-zone')
export class UploadZone extends CydonElement {

	connectedCallback() {
		initDropzone(this)
		super.connectedCallback()
		this.addEventListener('click', this.browse)
		resolves[0] = (files: string[]) => {
			if (files?.[0])
				this.dispatchEvent(new CustomEvent('file', {
					bubbles: true,
					detail: files
				}))
		}
		document.addEventListener('visibilitychange', () => {
			if (document.visibilityState == 'hidden')
				API.setDropzone(0, 0, 0)
		})
	}

	/** 选择文件 */
	browse(e: Event) {
		const el = <Element>e.currentTarget
		API.browseFile(el.hasAttribute('multiple')).then(resolves[0])
	}
}

declare global {
	interface HTMLElementTagNameMap {
		'upload-zone': UploadZone
	}
	interface HTMLElementEventMap {
		'file': CustomEvent<string[]>
	}
}